---
title: "Temp Token Model"
description: "Short-lived authentication tokens for secure handoffs"
---

## Overview

The TempToken model manages temporary authentication tokens used for secure app authentication flows. Tokens auto-expire after 60 seconds for security.

## Schema Structure

```typescript
{
  token: string,          // Unique token value
  userId: string,         // User who owns token
  packageName: string,    // App this token is for
  createdAt: Date,        // Creation time (TTL)
  used: boolean          // Usage tracking
}
```

## Field Purposes

### token (string)
Cryptographically secure random token:
- Generated using crypto.randomBytes
- Unique across all tokens
- Used as temporary credential

### userId (string)  
Links token to specific user:
- Ensures tokens can't be used by other users
- Enables user session lookup
- Audit trail for token usage

### packageName (string)
Specifies which app can use this token:
- Prevents token reuse across apps
- Security isolation between apps
- Usage analytics per app

### createdAt (Date)
Token creation timestamp with TTL:
- MongoDB TTL index auto-deletes after 60 seconds
- Prevents token accumulation
- Security through short lifespan

### used (boolean)
Tracks if token has been consumed:
- Prevents replay attacks
- One-time use enforcement
- Debugging token issues

## Usage Flow

### Token Generation
```typescript
// When app needs authentication
const token = crypto.randomBytes(32).toString('hex');
await TempToken.create({
  token,
  userId: 'user@example.com',
  packageName: 'com.translator.app'
});
```

### Token Validation
```typescript
// App presents token
const tempToken = await TempToken.findOne({ 
  token, 
  used: false 
});

if (tempToken && tempToken.packageName === appPackageName) {
  // Mark as used
  tempToken.used = true;
  await tempToken.save();
  
  // Generate real session token
  return generateAppToken(tempToken.userId, packageName);
}
```

## Security Features

### Auto-expiration
- 60-second TTL prevents long-lived tokens
- MongoDB automatically cleans up expired tokens
- No manual cleanup needed

### Single Use
- `used` flag prevents replay attacks
- Token invalid after first use
- Clear audit trail

### Scoped Access
- Token only valid for specific app
- Can't be used to authenticate other apps
- User-specific validation

## Common Use Cases

1. **App Authentication**: Secure handoff from mobile to app
2. **Deep Linking**: Temporary auth for URL-based flows
3. **OAuth-style Flows**: Short-lived authorization codes
4. **Password Reset**: Time-limited reset tokens

## Indexes

- **token**: Unique lookup
- **userId**: User's tokens
- **packageName**: App-specific queries
- **createdAt**: TTL index for auto-deletion